package com.linchong.source.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author linchong
 * @version 1.0
 * @Date: 2020-12-11 23:16
 * @Description: CGLibExample$
 */
public class CGLibExample {
	static class Car{
		public void running(){
			System.out.println("this car is running");
		}
	}

	static class CGLibProxy implements MethodInterceptor{

		// 代理对象
		private Object target;

		public Object getInstance(Object target){
			this.target = target;
			Enhancer enhancer = new Enhancer();
			// 设置父类为实例类
			enhancer.setSuperclass(this.target.getClass());
			// 回调方法
			enhancer.setCallback(this);
			// 创建代理对象
			return enhancer.create();
		}

		@Override
		public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
			System.out.println("方法调用前业务处理.");
			return methodProxy.invokeSuper(o, objects);
		}
	}

	public static void main(String[] args) {
		// 创建 CGLib 代理类
		CGLibProxy proxy = new CGLibProxy();
		// 初始化代理对象
		Car car = (Car) proxy.getInstance(new Car());
		// 执行方法
		car.running();
	}
}
